#include <SoftwareSerial.h>

#include <SD.h>
#include <DS3232RTC.h>  
// CS引脚为pin4，这里也沿用官方默认设置
const int chipSelect = 4;  //设定CS接口
SoftwareSerial BT(7, 8); //新建对象，接收脚为8，发送脚为9
void setup()
{
  Serial.begin(9600);  //设置串口通信波特率为9600
  BT.begin(9600); 
 setSyncProvider(RTC.get);   // the function to get the time from the RTC
    if(timeStatus() != timeSet)
        Serial.println("Unable to sync with the RTC");
    else
        Serial.println("RTC has set the system time");
  
  Serial.print("Initializing SD card...");  //串口输出数据Initializing SD card...
  pinMode(10, OUTPUT);
  
  
  if (!SD.begin(chipSelect)) {  //如果从CS口与SD卡通信失败，串口输出信息Card failed, or not present
    Serial.println("Card failed, or not present");
    return;
  }
  Serial.println("card initialized.");  //与SD卡通信成功，串口输出信息card initialized.
}

void loop()
{
  // 定义数组
  String dataString = "";
int i;
  // 读取三个传感器值，写入数组
if (BT.available()) {
  for (i = 0; i <= 9; i++)
    { if (BT.available())
        dataString+= BT.read();
      delay(5);
    }
    Serial.print(hour());
    printDigits(minute());
    printDigits(second());
    Serial.print(' ');
    Serial.print(day());
    Serial.print(' ');
    Serial.print(month());
    Serial.print(' ');
    Serial.print(year());
    Serial.println(dataString);
  // 打开文件，注意在同一时间只能有一个文件被打开
  // 如果你要打开另一个文件，就需要先关闭前一个
  File dataFile = SD.open("datalog.txt", FILE_WRITE);  

  // 打开datalog.txt文件，读写状态，位置在文件末尾。
  if (dataFile) {
        dataFile.print(year());
            dataFile.print(' ');
         dataFile.print(month());
             dataFile.print(' ');
      dataFile.print(day());
    dataFile.print(' ');
    dataFile.print(hour());
     dataFile.print(':');
    dataFile.print(minute());
     dataFile.print(':');
    dataFile.print(second());
         dataFile.print(':');
    dataFile.println(dataString);
    dataFile.close();
    // 数组dataString输出到串口
    Serial.println(dataString);
  }  
  // 如果无法打开文件，串口输出错误信息error opening datalog.txt
  else {
    Serial.println("error opening datalog.txt");
  } 

}
}

void printDigits(int digits)
{
    // utility function for digital clock display: prints preceding colon and leading 0
    Serial.print(':');
    if(digits < 10)
        Serial.print('0');
    Serial.print(digits);
}
